/**
 * com.dingjian.basedata.person.controller.PersonEditController.java
 */
package com.dingjian.basedata.person.controller;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import com.dingjian.base.CoreEntity;
import com.dingjian.base.service.BaseService;
import com.dingjian.base.util.StringUtils;
import com.dingjian.basedata.person.enums.UserStatusEnum;
import com.dingjian.basedata.person.model.Person;
import com.dingjian.basedata.person.model.PersonPosition;
import com.dingjian.basedata.person.service.PersonService;
import com.dingjian.framework.base.controller.EditController;

/**
 * @author FengMy
 *
 * @since 2012-10-9
 */
@Controller
@RequestMapping(value="basedata/person/*")
public class PersonEditController extends EditController {
	@Autowired
	private PersonService personService;
	@Override
	protected Class<Person> getSubmitClass() {
		return Person.class;
	}

	@Override
	protected BaseService<Person> getService() {
		return personService;
	}
	
	@SuppressWarnings("unchecked")
	@Override
	public void save(HttpServletResponse response)
			throws InstantiationException, IllegalAccessException {
		Person data = (Person) getSubmitEntity();
		String position = getString("positionJson");
		List<PersonPosition> pps = new ArrayList<PersonPosition>();
		if(!StringUtils.isEmpty(position)){
			pps = new ArrayList<PersonPosition>(JSONArray.toCollection(JSONArray.fromObject(position), PersonPosition.class));
		}
		if(validate(data)){
			if(data instanceof CoreEntity){
				if(StringUtils.isEmpty(((CoreEntity)data).getId())){
					data.setUserName(data.getNumber());
					data.setStatus(UserStatusEnum.DISABLED);
					personService.addPerson(data, pps);
				}else{
					personService.updatePerson(data, pps);
				}
				getOutputMsg().put("STATE", "SUCCESS");
				getOutputMsg().put("MSG", "保存成功");
			}
		}
		outPrint(response, JSONObject.fromObject(getOutputMsg(), getDefaultJsonConfig()));
	}
}
